import numpy

# it will compare the second value to each element in the vector
# if the values are equal, the Python interpreter returns
# True; otherwise False
vector = numpy.array([5, 10, 15, 20])
# output: array([False,  True, False, False], dtype=bool)
print(vector == 10)

# Compares vector to the value 10, which generates a new Boolean vector [False, True, False, False].
# It assigns this result to equal_to_ten
equal_to_ten = (vector == 10)
# output: 10
print(vector[equal_to_ten])

matrix = numpy.array([[5, 10, 15],
                      [20, 25, 30],
                      [35, 40, 45]])
print(matrix == 25)
second_column_25 = (matrix[:, 1] == 25)
print(second_column_25)
# output: 元素中有等于25的行
print(matrix[second_column_25, :])

# 输出等于10且等于5的元素
equal_to_ten_and_five = (vector == 10) & (vector == 5)
print(equal_to_ten_and_five)
# 输出等于10或等于5的元素
equal_to_ten_or_five = (vector == 10) | (vector == 5)
print(equal_to_ten_or_five)

# 将等于true的元素赋值为50
vector[equal_to_ten_or_five] = 50
print(vector)

# 类型转换
vector = numpy.array(["1", "2", "3"])
print(vector.dtype)
vector = vector.astype(float)
print(vector.dtype)
print(vector)

# 求和
print(vector.sum())

# max
print(vector.max())

# 行-1， 列-0 进行操作
matrix = numpy.array([[5, 10, 15],
                      [20, 25, 30],
                      [35, 40, 45]])
print(matrix.sum(axis=1))
print(matrix.sum(axis=0))

''''
综合的一个小例子，把前边学的知识综合起来：
'''
world_alcohol = numpy.genfromtxt('world_alcohol.txt', delimiter=',')
print(type(world_alcohol))
# return bool
is_value_empty = numpy.isnan(world_alcohol[:, 4])
print(is_value_empty)

# 把空值替换成 ‘0’ 字符
world_alcohol[is_value_empty, 4] = '0'
alcohol_consumption = world_alcohol[:, 4]
# 把字符转换成float
alcohol_consumption = alcohol_consumption.astype(float)
# 总消耗
total_alcohol = alcohol_consumption.sum()
# 平均消耗
average_alcohol = alcohol_consumption.mean()
# print(world_alcohol[:,4])
print(total_alcohol)
print(average_alcohol)
